var counsel = new Application();

counsel.Router = Backbone.Router.extend({

    routes: {
        "":                         "welcome",
        "me":                       "me",
		"requests":         		"requests",
        "categories":               "categories",
        "person/:id":               "userprofile",
        "categories/:id":    		"usersincategories",
        "person/:id/reviews": 		"userreview",
        "person/:id/startCounsel": 	"startCounsel",
		"person/:id/counsel": 		"counsel",
		"categories/:id/addUser":	"addUserToCategory"
    },

    initialize: function() {
        // Caching the Welcome View
        this.welcomeView = new counsel.views.Welcome({model: counsel.user});
    },

    welcome: function () {
        $('#content').html(this.welcomeView.el);
    },

    me: function () {

		this.userprofile(-1);

    },

	requests: function () {
		$('#content').html('');
		  var self = this;
		  try {
			  jQuery.ajax({
				   url: 'counsel/user',
				   type: 'GET',
				   success: function (data){
					   $('#content').append(new counsel.views.MyRequests({model: new Backbone.Model(data)}).el);
				   }
				  });
	        } catch (e) {
	            this.showErrorPage();
	        }

    },

	categories: function () {
		$('#content').html('');
		var self = this;
		try{

			jQuery.ajax({
				   url: 'category',
				   type: 'GET',
				   success: function (data){
					   $('#content').append(new counsel.views.Categories({model: new Backbone.Model(data)}).el);
				   }
				  });
			
		} catch (e) {
            this.showErrorPage();
        }
		

    },
    
    
    addUserToCategory: function (id) {
		var self = this;
		try{

			jQuery.ajax({
				   url: 'category/'+id+'/addUser',
				   type: 'GET',
				   success: function (data){
					   
					   $('.addToCategory').hide();
				   }
				  });
			
		} catch (e) {
            this.showErrorPage();
        }
		

    },


    userprofile: function (id) {
	$('#content').html('');
          var self = this;
        try {
        	jQuery.ajax({
				   url: 'user/'+id,
				   type: 'GET',
				   success: function (data){
					   if(id == -1){
						   $('#content').append(new counsel.views.MySelf({model: new counsel.models.Person(data)}).el); 
					   }else{
					   $('#content').append(new counsel.views.Person({model: new Backbone.Model(data)}).el);
				   }
				   }
				  });
        } catch (e) {
            this.showErrorPage();
        }
    },

    usersincategories: function (id) {
        var self = this;
        $('#content').html('');
        try {
        	jQuery.ajax({
				   url: 'category/'+id+'/user',
				   type: 'GET',
				   success: function (data){
					   $('#content').append(new counsel.views.Users({model: new Backbone.Model(data)}).el);
				   }
				  });
        } catch (e) {
            this.showErrorPage();
        }
    },

    userreview: function (id) {
        var self = this;
	  try {
		   jQuery.ajax({
			   url: "/user/" + id + "/review",
			   type: 'GET',
			   success: function (data){
				   $('#content').append(new counsel.views.Reviews({model: new Backbone.Model(data)}).el);
			   }
			  });
        } catch (e) {
            this.showErrorPage();
        }
    },
    
    
    startCounsel: function (id) {
    	var myModel = new Backbone.Model();

		myModel.set("eventId", id);
		
    	$('#content').html('');
	    $('#content').append(new counsel.views.OpenTok({ model: myModel }).el);
	
    	jQuery.ajax({
			url: 'counsel/'+id+'/session',
			type: 'GET',
			success: function (data){
				
				openTokData = data;
				alert(eval(openTokData).apiKey);
				if(openTokData != null && openTokData != 'undefined'){
					
					
					if (TB.checkSystemRequirements() != TB.HAS_REQUIREMENTS) {
						alert("You don't have the minimum requirements to run this application."
								+ "Please upgrade to the latest version of Flash.");
					} else {
						 session = TB.initSession(openTokData.sessionId); // Initialize session
						 
						 session.addEventListener('sessionConnected', sessionConnectedHandler);
					     session.addEventListener('streamCreated', streamCreatedHandler);
					     TB.addEventListener("exception", exceptionHandler);
					     TB.setLogLevel(TB.DEBUG);
					     session.connect(openTokData.apiKey, openTokData.moderatorToken);
					     
					}
					  			     
				}
			}
		});
			
       
    },
    
    
   
	counsel: function (id) {
		var myModel = new Backbone.Model();

		myModel.set("frmUserId", id);
		
        $('#content').html('');
        $('#content').append(new counsel.views.Counsel({ model: myModel }).el);
    },

    showErrorPage: function () {
        $('#content').append(new counsel.views.Error().el);
    }

});

$(document).on('ready', function() {
    counsel.user = new counsel.models.Person(); // Holds the authenticated Facebook user
    // Load HTML templates for the app
    counsel.templateLoader.load(['shell', 'welcome', 'login', 'myself','person', 'categories', 'users', 'notifications','myrequests','counsel','reviews','opentok'], function () {
        counsel.shell = new counsel.views.Shell({el: "#shell", model: counsel.user});
        counsel.router = new counsel.Router();
        Backbone.history.start();
    });
});

$(document).on('fbStatusChange', function (event, data) {
    if (data.status === 'connected') {
    	
        FB.api('/me', function(response) {
        	
        	var reqData = {"email" : response.email, "name": response.first_name, "emailValidated": response.verified, "imagePath":"http://graph.facebook.com/"+response.id+"/picture?width=150&height=150"};
         	jQuery.ajax({
				   url: 'login',
				   type: 'POST',
				   contentType : "application/json",
				   traditional: true,
				   data :  JSON.stringify(reqData),
				   success: function (data){
					   counsel.user.set(data); 
				   }
			});
        });
    
    } else {
        counsel.user.set(counsel.user.defaults); // Reset current FB user
    }
});

$(document).on('logout', function () {
	jQuery.ajax({
		   url: 'logout',
		   type: 'GET',
		   contentType : "application/json",
		   traditional: true,
		   success: function (data){
			   FB.logout();
			   return false;
		   }
	});
  
});

$(document).on('login', function () {
    FB.login(function(response) {
    	
    	 if (response.authResponse) {
    	        var accessToken = response.authResponse.accessToken;
    	 
    	            
          } else {
            console.log('User cancelled login or did not fully authorize.');
          }
    }, {scope: 'publish_actions,email'});
    return false;
});